package com.sky.sky_server.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sky.sky_common.context.BaseContext;
import com.sky.sky_pojo.entity.AddressBook;
import com.sky.sky_server.mapper.AddressBookMapper;
import com.sky.sky_server.service.AddressBookService;

@Service
public class AddressBookServiceImpl implements AddressBookService{
    @Autowired
    private AddressBookMapper adressBookMapper;

    /**
     * 添加地址簿
     */
    @Override
    public int addAddressBook(AddressBook adressBook) {
        Long userId = BaseContext.getCurrentId();
        adressBook.setUserId(userId);
        adressBook.setIsDefault(0);
        return adressBookMapper.insert(adressBook);
    }

    /**
     * 查看地址簿
     */
    @Override
    public List<AddressBook> list() {
        Long userId = BaseContext.getCurrentId();
        return adressBookMapper.listByUserId(userId);
    }

    /**
     * 查看默认地址簿
     */
    @Override
    public AddressBook defaultAdressBook() {
        Long userId = BaseContext.getCurrentId();
        return adressBookMapper.getDefaultAddressBook(userId);
    }

    /**
     * 根据id修改地址簿
     */
    @Override
    public int updateAddressBook(AddressBook adressBook) {
        return adressBookMapper.updateAddressBookById(adressBook);
    }

    /**
     * 修改默认地址簿
     */
    @Override
    @Transactional
    public int updateDefaultAddressBook(Long id) {
        Long userId = BaseContext.getCurrentId();
        // 将该用户的所有地址簿的isDefault字段设置为0
        adressBookMapper.updateIsDefaultToZero(userId);
        // 将指定id的地址簿的isDefault字段设置为1
        int res = adressBookMapper.updateIsDefaultToOne(id);
        if(res <= 0)
            throw new RuntimeException("修改默认地址簿失败");
        return res;
    }

    @Override
    public AddressBook getById(Long id) {
        return adressBookMapper.getById(id);
    }

    @Override
    public int delete(Long id) {
        return adressBookMapper.deleteById(id);
    }
}
